package com.xcity.game.task.detector;

import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import com.xcity.db.entity.Build;
import com.xcity.game.task.Task;
import com.xcity.game.task.TaskDetector;
import com.xcity.game.task.TaskDetectorLabel;

/**
 * <pre>
 * 建筑收钱(次数)
 * 2个参数:
 * 1.建筑id(0:任意建筑)
 * 2.次数
 * </pre>
 * @author yang.li
 *
 */
@TaskDetectorLabel(TaskDetector.BUILD_INCOME)
public class BuildIncomeTaskDetector implements TaskDetector {

	static final String KEY = String.valueOf(BUILD_INCOME);
	
	@Override
	public boolean isFinish(Task task) {
		int[] conds = task.getTemplate().getConditions();
		int buildId = conds[0];
		int n = conds[1];
		JSONObject builds = task.getArchive().getJSONObject(KEY);
		if (builds == null) {
			return false;
		}
		if (buildId != 0) {
			return builds.getIntValue(String.valueOf(buildId)) >= n;
		}
		Set<String> ids = builds.keySet();
		int total = 0;
		for (String id : ids) {
			if ((total += builds.getIntValue(id)) >= n) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void onArchive(Task task, Object... vals) {
		// { 7: { buildId: n } }
		JSONObject builds = task.getArchive().getJSONObject(KEY);
		if (builds == null) {
			builds = new JSONObject();
			task.getArchive().put(KEY, builds);
		}
		Build b = (Build) vals[1];
		String buildId = String.valueOf(b.getId());
		builds.put(buildId, builds.getIntValue(buildId) + 1);
	}

}
